package com.zl.roomdesignserver.service;

import com.zl.roomdesignserver.entity.auth.User;
import com.zl.roomdesignserver.exception.ControllerException;
import com.zl.roomdesignserver.repository.AuthRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Optional;

/**
 * Created by zhangli on 2018/5/5 14:09.<br/>
 */
@Service
public class AuthService {

    @Autowired
    AuthRepository authRepository;

    public Object register(User user) {

        if (!String.valueOf(user.getPhone()).matches("1\\d{10}")) {
            throw new ControllerException("手机号码错误");
        } else if (StringUtils.isEmpty((user.getName()))
                || StringUtils.isEmpty((user.getPassword()))) {
            throw new ControllerException("注册信息不完整");
        }

        Optional<User> userOptional = authRepository.findById(user.getPhone());
        if (userOptional.isPresent()) {
            throw new ControllerException("用户已存在");
        }

        User u = new User();
        u.setPhone(user.getPhone());
        u.setName(user.getName());
        u.setPassword(user.getPassword());
        authRepository.save(u);
        return null;
    }

    public User login(User user) {
        Optional<User> userOptional = authRepository.findById(user.getPhone());
        if (!userOptional.isPresent()) {
            throw new ControllerException("用户不存在");
        } else {
            User one = userOptional.get();
            if (!one.getPassword().equals(user.getPassword())) {
                throw new ControllerException("密码错误");
            }
            return one;
        }
    }
}
